package com.gin.kotlin.no_gay_alliance.fragment.topiclist

import android.os.Message
import android.util.Log
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import androidx.core.view.MenuProvider
import androidx.viewbinding.ViewBinding
import com.gin.kotlin.no_gay_alliance.R
import com.gin.kotlin.no_gay_alliance.activity.BlockedTopicsActivity
import com.gin.kotlin.no_gay_alliance.activity.ReplyListActivity
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.argument.ReplyListArgument
import com.gin.kotlin.no_gay_alliance.argument.ReplyListArgument.Type
import com.gin.kotlin.no_gay_alliance.base.ClipboardUtils
import com.gin.kotlin.no_gay_alliance.callback.RCallback
import com.gin.kotlin.no_gay_alliance.enums.HandlerMessageWhat
import com.gin.kotlin.no_gay_alliance.model.ForumEntryModel
import com.gin.kotlin.no_gay_alliance.provider.ngaphp.FavorForumProvider
import com.gin.kotlin.no_gay_alliance.store.GlobalProperty
import com.gin.nga.callback.NgaCallback
import com.gin.nga.response.base.NgaResponse
import com.gin.nga.response.topic.TopicInfo
import retrofit2.Call
import retrofit2.Response

/**
 * 版面浏览和合集浏览的公共父类
 * @param T : ViewBinding
 * @property tvTopMenuBlocked 顶部按钮：屏蔽
 * @property blockedTopics 被屏蔽主题
 */
abstract class BaseTopicListFragment<T : ViewBinding> : AbstractTopicListFragment<T>(), MenuProvider, View.OnClickListener, NgaCallback<List<String>> {
    private var tvTopMenuBlocked: TextView? = null
    private var blockedTopics: List<TopicInfo>? = null

    override fun onCreateView() {
        super.onCreateView()
        this.tvTopMenuBlocked = b?.root?.findViewById(R.id.tv_top_menu_blocked)
    }

    override fun onPrepareMenu(menu: Menu) {
        super.onPrepareMenu(menu)
        //管理菜单中的：已关注，未关注按钮
        val miFollowable = menu.findItem(R.id.mi_followable)
        val miFollowed = menu.findItem(R.id.mi_followed)

        FavorForumProvider.getInstance().enqueue(callback = object : RCallback<List<ForumEntryModel>, Nothing> {
            override fun onSuccess(data: List<ForumEntryModel>, ignoreCache: Boolean) {
                // 版面ID或合集ID
                val id = argument.colTid ?: argument.forumId ?: currentForum?.colTid ?: currentForum?.forumId
                val followed = data.any { it.entryId == id }
                ui {
                    miFollowable.isVisible = !followed
                    miFollowed.isVisible = followed
                }
            }

            override fun onError(errorMessage: String) {
                Log.w(TAG, "收藏版面获取失败: $errorMessage")
            }
        })

    }

    override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
        // 搜索
        menuInflater.inflate(R.menu.search, menu)
        //装载通用菜单 提醒、私信、主题浏览历史、举报记录、回复历史
        menuInflater.inflate(R.menu.common_menu, menu)
        // 复制代码、复制链接
        menuInflater.inflate(R.menu.copy, menu)
        // 已关注、未关注
        menuInflater.inflate(R.menu.follow, menu)
    }

    override fun handleMessage(msg: Message): Boolean {
        when (msg.what) {
            HandlerMessageWhat.BLOCKED_TOPICS.ordinal -> {
                @Suppress("UNCHECKED_CAST")
                blockedTopics = msg.obj as? List<TopicInfo>
                // 设置屏蔽按钮文字及可见性
                this.tvTopMenuBlocked?.visibility = if (blockedTopics.isNullOrEmpty()) View.GONE else View.VISIBLE
                this.tvTopMenuBlocked?.text = getString(R.string.tv_top_menu_blocked, (blockedTopics?.size ?: 0).toString())

                return true
            }
        }


        return super.handleMessage(msg)
    }

    /**
     * 公共的菜单相应项目
     */
    override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
        val colTid = argument.colTid ?: currentForum?.colTid
        val forumId = if (colTid != null) null else argument.forumId ?: currentForum?.forumId
        val forumApi = App.INSTANCE.ngaApi.forumApi
        return when (menuItem.itemId) {
            R.id.mi_followable -> {
                Log.i(TAG, "关注: ")
                forumApi.favorAdd(forumId, colTid).enqueue(this)
                true
            }

            R.id.mi_followed -> {
                Log.i(TAG, "取关: ")
                forumApi.favorDel(forumId, colTid).enqueue(this)
                true
            }

            R.id.mi_copy_link -> {
                currentForum?.obtainUrl(GlobalProperty.getInstance().domain)?.also {
                    Log.i(TAG, "已复制: $it")
                    ClipboardUtils.setText(it, requireContext())
                    toast("已复制链接")
                }
                true

            }

            R.id.mi_copy_code -> {
                (currentForum?.getColBbsCode() ?: currentForum?.getBbsCode())
                    ?.also {
                        Log.i(TAG, "已复制: $it")
                        ClipboardUtils.setText(it, requireContext())
                        toast("已复制代码")
                    }
                true

            }

            else -> false
        }
    }

    /**
     * 公共点击相应
     */
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_top_menu_top_topic -> {
                val id = currentForum?.colTid ?: currentForum?.toppedTopicId
                Log.i(TAG, "打开版头主题: $id")
                ReplyListActivity.startActivity(requireContext(), ReplyListArgument(Type.LIST, topicId = id))
            }

            R.id.tv_top_menu_blocked -> {
                Log.i(TAG, "打开已屏蔽主题列表: ")
                val list = blockedTopics
                if (!list.isNullOrEmpty()) BlockedTopicsActivity.start(requireContext(), list)
            }
        }
    }

    override fun onSuccess(call: Call<NgaResponse<List<String>>>, response: Response<NgaResponse<List<String>>>, body: NgaResponse<List<String>>?, data: List<String>?) {
        // 发送消息，更新收藏版面信息
        data?.get(0)?.also { toast(it) }
        FavorForumProvider.getInstance().enqueue(ignoreCache = true)
    }

    override fun onError(call: Call<NgaResponse<List<String>>>, response: Response<NgaResponse<List<String>>>, body: NgaResponse<List<String>>?, errorMessage: String) {
        super.onError(call, response, body, errorMessage)
        toastLong(errorMessage)
    }
}